//
//  IMAChatViewController.m
//  TIMChat
//
//  Created by AlexiChen on 16/3/17.
//  Copyright © 2016年 AlexiChen. All rights reserved.
//

#import "IMAChatViewController.h"
#import <ReactiveCocoa.h>
#import <IQKeyboardManager.h>
#import "XLHTTPSessionManager+matchOrder.h"
#import "XLOrderViewController.h"
#import "XLAccountManager.h"
#import "XLNewOrderViewController.h"
#import "TopUpViewController.h"
#import "UIView+Layout.h"
#import "FBKVOController.h"
#import "NSObject+FBKVOController.h"


@implementation IMAChatViewController{
    UIButton *giftButton;
    
    //是否预先请求金豆数目
    BOOL isCanSend;
    //剩余金豆
    NSInteger beansCount;
    
    //是否请求数据失败
    BOOL requestSucess;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}

- (void)dealloc
{
    [self.KVOController unobserveAll];
    _isScrool = NO;
    [giftButton removeFromSuperview];
    [_conversation releaseConversation];
    _messageList = nil;
    _tableView.delegate = nil;
    _tableView.dataSource = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    if (_ChatViewBackBlock) {
        _ChatViewBackBlock ();
    }
    
    //退出时上报一次已读，以前是没收到一条消息都上报，会导致server接收到大量的已读上报消息
    [_conversation setReadAllMsg];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = YES;
    manager.shouldShowToolbarPlaceholder = YES;
    manager.enableAutoToolbar = YES;
    giftButton.hidden = YES;
    //    [_inputView endEditing:YES];
    //    [_inputView resignFirstResponder];
    self.isAppear = NO;
    
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //是否首先请求金豆数目
    //    isCanSend = NO;
    
    self.view.backgroundColor = kWhiteColor;
    [self showBackButton:NULL];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onDeleteMsg:) name:kIMAMSG_DeleteNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onResendMsg:) name:kIMAMSG_ResendNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onChangedMsg:) name:kIMAMSG_ChangedNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onfuzhiMsg:) name:@"fuzhi" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hiddenKeyBoard) name:@"celltap" object:nil];
    
    self.fd_interactivePopDisabled = YES;
    _isScrool = YES;
    //[self addObserver];
    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"])
    {
        //[self StartGrabSingle];
    }
    
    //请求金豆数目 是否可以发送消息请求信息
    
    //判断主播 / 用户
    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"0"]) {
        //请求信息 防止发送信息请求的时候 请求数据缓慢
        [[[XLHTTPSessionManager sharedManager] XLV2GET:@"/api/v2/Balance/GetUserBalance" parameters:@{@"userId":[[XLAccountManager shareInstance]model].Id} resultClass:nil]subscribeNext:^(id x) {
            NSDictionary *dic = x;
            
            requestSucess = YES;
            
            //获取金豆总数
            NSString *totalMoney = [NSString stringWithFormat:@"%.1lf",[[dic objectForKey:@"AccountBalance"] floatValue]];
            
            CGFloat beans = [totalMoney floatValue]*10;
            beansCount = beans;
            
        } error:^(NSError *error) {
            
            requestSucess = NO;
            [self setRequestSource:nil];
            
        }];
        
    }
    
    
}

//请求金豆数目
- (void)reqeustSource
{
    
    //判断主播 / 用户
    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"]) {
        return;
    }
    
    [[[XLHTTPSessionManager sharedManager] XLV2GET:@"/api/v2/Balance/GetUserBalance" parameters:@{@"userId":[[XLAccountManager shareInstance]model].Id} resultClass:nil]subscribeNext:^(id x) {
        NSDictionary *dic = x;
        
        requestSucess = YES;
        
        [self setRequestSource:dic];
        
    } error:^(NSError *error) {
        
        requestSucess = NO;
        [self setRequestSource:nil];
        
    }];
}

//操作请求信息 判断金豆数是否需要提示
- (void)setRequestSource:(NSDictionary *)dic
{
    //获取金豆总数
    NSString *totalMoney = [NSString stringWithFormat:@"%.1lf",[[dic objectForKey:@"AccountBalance"] floatValue]];
    
    CGFloat beans = [totalMoney floatValue]*10;
    beansCount = beans;
    
    
    if (beansCount <= 0 && requestSucess == YES) {
        
        //金豆不够使用
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"金豆余额不足" message:@"快去充值开启你的畅聊吧" preferredStyle:(UIAlertControllerStyleAlert)];
        
        UIAlertAction *alertRecharge = [UIAlertAction actionWithTitle:@"充值" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
            //跳转充值界面
            TopUpViewController *topViewVc = [[TopUpViewController alloc] init];
            [self.navigationController pushViewController:topViewVc animated:YES];
            
        }];
        
        UIAlertAction *alertCancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        //添加弹窗事件
        [alertVc addAction:alertRecharge];
        [alertVc addAction:alertCancel];
        
        [self presentViewController:alertVc animated:YES completion:^{
            
        }];
    }else{
        
        //请求失败 可以发送消息
        if (requestSucess == NO) {
            beansCount = 10;
        }else{
            beansCount = beans;
        }
        
    }
    
}



- (void)addObserver {
    @weakify(self);
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"OrderRefresh" object:nil] subscribeNext:^(id x) {
        @strongify(self);
        if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"]){
            if (self.isAppear) {
                [self userOderListData];
            }
        }
    }];
}

#pragma mark -
#pragma mark - 开始抢单
-(void)StartGrabSingle
{
    _beautyTopView = [[UIView alloc] init];
    _beautyTopView.backgroundColor = kClearColor;
    [self.view addSubview:_beautyTopView];
    [self hostTapGestureRecognizer:_beautyTopView];
    [_beautyTopView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right).offset(-15);
        make.bottom.equalTo(self.view.mas_bottom).offset(-100);
        make.size.mas_equalTo(CGSizeMake(48, 48));
    }];
    _videochatTopImg = [[UIImageView alloc] init];
    _videochatTopImg.image = [UIImage imageNamed:@"home_but_qiang2_n"];
    [_beautyTopView addSubview:_videochatTopImg];
    [_videochatTopImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(_beautyTopView);
        make.size.mas_equalTo(CGSizeMake(48, 48));
    }];
    _redPoint = [[UILabel alloc] init];
    _redPoint.textColor = kWhiteColor;
    _redPoint.font = kSetFont(10);
    _redPoint.layer.masksToBounds = YES;
    _redPoint.layer.cornerRadius  = 8;
    _redPoint.backgroundColor = RGBA(248, 75, 90, 1);
    _redPoint.textAlignment = NSTextAlignmentCenter;
    [_videochatTopImg addSubview:_redPoint];
    
}
- (void)updateCellOnline
{
    NSInteger readCount = self.orderInter;
    if ( readCount <= 9 &&  readCount > 0)
    {
        _redPoint.hidden = NO;
        [_redPoint mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(20, 16));
            make.center.equalTo(_videochatTopImg).centerOffset(CGPointMake(18, -9));
        }];
        
    }else if (readCount >= 10) {
        _redPoint.hidden = NO;
        [_redPoint mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(30, 20));
            make.center.equalTo(_videochatTopImg).centerOffset(CGPointMake(18, -9));
        }];
        
    }else {
        _redPoint.hidden = YES;
        [_redPoint mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(0, 0));
            make.center.equalTo(_videochatTopImg).centerOffset(CGPointMake(18, -9));
        }];
        
    }
    [_redPoint setText:readCount > 99 ? @"99+" : [NSString stringWithFormat:@"%ld",readCount]];
}

-(void)hostTapGestureRecognizer:(UIView *)view
{
    UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc]initWithTarget:self     action:@selector(hostTapAction:)];
    [view addGestureRecognizer:tap];
}

#pragma mark -
#pragma mark -主播-抢单大厅
-(void)hostTapAction:(UITapGestureRecognizer *)tap
{
    //主播-抢单大厅
    NSLog(@"主播-抢单大厅");
    if ([self checkCameraAuthorization]) {
        XLNewOrderViewController *vc = [[XLNewOrderViewController alloc] init];
        vc.view.backgroundColor=[UIColor colorWithWhite:0 alpha:0.77];
        vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
        [self presentViewController:vc animated:YES completion:^(void){
            vc.view.superview.backgroundColor = [UIColor clearColor];
        }];
    }
}

-(void)userOderListData
{
    [[[XLHTTPSessionManager sharedManager] getOrderListWithAnchorId:[[XLAccountManager shareInstance] model].Id] subscribeNext:^(id x) {
        NSLog(@"订单列表数据==%@",x);
        self.orderListAry = x;
        if (self.orderListAry.count > 0 || self.orderListAry.count == 0) {
            self.orderInter = self.orderListAry.count;
            [self updateCellOnline];
        }
        
    } error:^(NSError *error) {
        
    }];
}

#pragma mark - 检测相机的权限是否开启
- (BOOL)checkCameraAuthorization {  //检测相机是否可用和有无授权
    BOOL isCameraAvailable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
    
    if (!isCameraAvailable) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前设备无法使用摄像头" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return isCameraAvailable;
    }
    BOOL isAvalible = YES;
    //ios 7.0以上的系统新增加摄像头权限检测
    if (iOS7) {
        //获取对摄像头的访问权限。
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        switch (authStatus) {
            case AVAuthorizationStatusRestricted://此应用程序没有被授权访问的照片数据。可能是家长控制权限。
                break;
            case AVAuthorizationStatusDenied://用户已经明确否认了这一照片数据的应用程序访问.
                isAvalible = NO;
                break;
            case AVAuthorizationStatusAuthorized://用户已授权应用访问照片数据.
                break;
            case AVAuthorizationStatusNotDetermined://用户尚未做出了选择这个应用程序的问候
                isAvalible =[UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
                break;
            default:
                break;
        }
    }
    AVAuthorizationStatus statusAudio = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (statusAudio == AVAuthorizationStatusDenied) {
        isAvalible = NO;
    }
    
    if (!isAvalible) {
        //[self analyticsEvent14];
        NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
        NSString *appName = [infoDict objectForKey:@"CFBundleDisplayName"];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:F(@"您关闭了%@的相机/麦克风权限，无法进行拍照。可以在手机 > 设置 > 隐私 > 相机和麦克风中开启权限。", appName) preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:NULL];
        [alert addAction:action1];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        [alert addAction:action2];
        
        
        [self presentViewController:alert animated:YES completion:NULL];
        
    }
    return isAvalible;
}

- (void)onfuzhiMsg:(NSNotification *)notify {
    IMAMsg *msg = (IMAMsg *)notify.object;
    TIMElem *elem = [msg.msg getElem:0];
    
    if ([elem isKindOfClass:[TIMCustomElem class]]) {
        
    }else if ([elem isKindOfClass:[TIMTextElem class]]) {
        TIMTextElem *elem = (TIMTextElem *)[msg.msg getElem:0];
        NSLog(@"ssss :  %@ === ",elem.text);
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.string = elem.text;
        NSLog(@"\r\n====>输入框内容为:%@n====>",pasteboard.string);
        
    }
    NSLog(@"ddd :  %@ === ",msg.msg);
    
}
- (void)showBackButton:(void (^)(void))clickBlock{
    if ([_receiver isC2CType]) {
        UIView *navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
        //        navView.backgroundColor = [UIColor redColor];
        UIButton *backButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44, 44)];
        [backButton setImageEdgeInsets:UIEdgeInsetsMake(0, -30, 0, 0)];
        
        UIImage *backImg = [UIImage imageNamed:@"common_nav_btn_back_n"];
        backImg = [backImg imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        [backButton setImage:backImg forState:UIControlStateNormal];
        
        //        UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(44, 0, 100, 44)];
        //        titleLab.text = [_receiver showTitle];
        //        titleLab.textAlignment = NSTextAlignmentLeft;
        [navView addSubview:backButton];
        //        [navView addSubview:titleLab];
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:navView];
        
        @weakify(self);
        [[backButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            @strongify(self);
            if (clickBlock) {
                clickBlock();
            }else{
                self.isback = YES;
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
        
    }else {
        UIButton *backButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44, 44)];
        [backButton setImageEdgeInsets:UIEdgeInsetsMake(0, -30, 0, 0)];
        
        UIImage *backImg = [UIImage imageNamed:@"common_nav_btn_back_n"];
        backImg = [backImg imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        [backButton setImage:backImg forState:UIControlStateNormal];
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backButton];
        
        @weakify(self);
        [[backButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            @strongify(self);
            if (clickBlock) {
                clickBlock();
            }else{
                [[NSNotificationCenter defaultCenter] removeObserver:self];
                
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
        
    }
    
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
    giftButton.hidden = NO;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    self.isAppear = YES;
    
    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"])
    {
        //[self userOderListData];
    }
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = NO;
    manager.shouldResignOnTouchOutside = NO;
    manager.shouldToolbarUsesTextFieldTintColor = NO;
    manager.shouldShowToolbarPlaceholder = NO;
    manager.enableAutoToolbar = NO;
}

- (void)onDeleteMsg:(NSNotification *)notify
{
    IMAMsg *msg = (IMAMsg *)notify.object;
    __weak IMAChatViewController *ws = self;
    [_conversation removeMsg:msg completion:^(NSArray *imamsgList, BOOL succ, NormalVoidBlock removingAction) {
        if (succ)
        {
            [ws onWillRemove:imamsgList withAction:removingAction];
        }
    }];
}

- (void)onResendMsg:(NSNotification *)notify
{
    IMAMsg *msg = (IMAMsg *)notify.object;
    __weak IMAChatViewController *ws = self;
    [_conversation removeMsg:msg completion:^(NSArray *imamsgList, BOOL succ, NormalVoidBlock removingAction) {
        if (succ)
        {
            [ws onWillRemove:imamsgList withAction:removingAction];
        }
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self sendMsg:msg];
    });
    
}

- (void)onChangedMsg:(NSNotification *)notify
{
    IMAMsg *msg = (IMAMsg *)notify.object;
    
    NSInteger idx = [_conversation.msgList indexOfObject:msg];
    if (idx >= 0 && idx < _conversation.msgList.count)
    {
        [_tableView beginUpdates];
        NSIndexPath *index = [NSIndexPath indexPathForRow:idx inSection:0];
        [_tableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationFade];
        [_tableView endUpdates];
    }
}

- (void)addInputPanel
{
    if ([[[XLAccountManager shareInstance] model].IsAnchor integerValue] == 10) {
        //永远不会执行到这里  应为是否是主播只会有0，1
        _inputView = [[ChatInputPanel alloc] initWithchatType:[_receiver isC2CType]];
        _inputView.type = [_receiver isC2CType];
        _inputView.chatDelegate = self;
        [self.view addSubview:_inputView];
    }else{
        giftButton = [UIButton buttonWithType:UIButtonTypeCustom];
        giftButton.frame = CGRectMake(SCREEN_WIDTH - 46, SCREEN_HEIGHT -160, 46, 40);
        [giftButton setBackgroundImage:[UIImage imageNamed:@"message_xuanfu_but_liwu_n"] forState:UIControlStateNormal];
        [giftButton addTarget:self action:@selector(moreVideFlowerAction) forControlEvents:UIControlEventTouchUpInside];
        
        [[[[UIApplication sharedApplication]delegate]window] addSubview:giftButton];
        _input2ViewUser = [[XLChatInputPanelUser alloc] initWithCahtType:[_receiver isC2CType] andUser:_receiver];
        _input2ViewUser.type = [_receiver isC2CType];
        _input2ViewUser.chatDelegate = self;
        [self.view addSubview:_input2ViewUser];
    }
    
}

- (void)addChatToolBar
{
    [self addInputPanel];
    
    self.KVOController = [FBKVOController controllerWithObserver:self];
    __weak IMAChatViewController *ws = self;
    if ([[[XLAccountManager shareInstance] model].IsAnchor integerValue] == 10) {
        [self.KVOController observe:_inputView keyPath:@"contentHeight" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld block:^(id observer, id object, NSDictionary *change) {
            [ws onInputViewContentHeightChanged:change];
        }];
    }else{
        
        [self.KVOController observe:_input2ViewUser keyPath:@"contentHeight" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld block:^(id observer, id object, NSDictionary *change) {
            [ws onInputViewContentHeightChanged:change];
        }];
    }
    
}

- (void)onInputViewContentHeightChanged:(NSDictionary *)change
{
    
    if (_isScrool) {
        NSInteger nv = [change[NSKeyValueChangeNewKey] integerValue];
        NSInteger ov = [change[NSKeyValueChangeOldKey] integerValue];
        giftButton.frame = CGRectMake(SCREEN_WIDTH - 46, SCREEN_HEIGHT - nv - 100, 46, 40);
        if (nv != ov)
        {
            // nv > ov 说明是展开，否则是缩回
            // TODO：界面消息较少时，下面的做法将顶部消息顶出去，可根据内容显示再作显示优化
            NSInteger off = nv - ov;
            if (_tableView.contentSize.height + off <= _tableView.bounds.size.height)
            {
                CGRect rect = _tableView.frame;
                rect.size.height -= off;
                _tableView.frame = rect;
            }
            else
            {
                CGRect rect = _tableView.frame;
                if (rect.origin.y == 0)
                {
                    rect.size.height -= off;
                    _tableView.frame = rect;
                }
                else
                {
                    rect.origin.y -= off;
                    _tableView.frame = rect;
                }
                if (off > 0)
                {
                    NSInteger toff = _tableView.contentSize.height - _tableView.frame.size.height;
                    if (toff < off )
                    {
                        if (toff > 0)
                        {
                            _tableView.contentOffset = CGPointMake(_tableView.contentOffset.x, _tableView.contentOffset.y + toff);
                        }
                    }
                    else
                    {
                        _tableView.contentOffset = CGPointMake(_tableView.contentOffset.x, _tableView.contentOffset.y + off);
                    }
                }
            }
        }
        
    }
}


- (void)layoutRefreshScrollView
{
    CGSize size = self.view.bounds.size;
    if (@available(iOS 11.0, *)) {
        
        if ([[[XLAccountManager shareInstance] model].IsAnchor integerValue] == 10) {
            _tableView.frame = CGRectMake(0, 0, size.width, size.height - _inputView.contentHeight - self.view.safeAreaInsets.bottom);
            [_inputView setFrameAndLayout:CGRectMake(0, size.height - _inputView.contentHeight - self.view.safeAreaInsets.bottom, size.width, _inputView.contentHeight)];
        }else{
            _tableView.frame = CGRectMake(0, 0, size.width, size.height - _input2ViewUser.contentHeight - self.view.safeAreaInsets.bottom);
            [_input2ViewUser setFrameAndLayout:CGRectMake(0, size.height - _input2ViewUser.contentHeight - self.view.safeAreaInsets.bottom, size.width, _input2ViewUser.contentHeight)];
        }
        
    } else {
        
        if ([[[XLAccountManager shareInstance] model].IsAnchor integerValue] == 10) {
            _tableView.frame = CGRectMake(0, 0, size.width, size.height - _inputView.contentHeight);
            [_inputView setFrameAndLayout:CGRectMake(0, size.height - _inputView.contentHeight, size.width, _inputView.contentHeight)];
        }else{
            _tableView.frame = CGRectMake(0, 0, size.width, size.height - _input2ViewUser.contentHeight);
            [_input2ViewUser setFrameAndLayout:CGRectMake(0, size.height - _input2ViewUser.contentHeight, size.width, _input2ViewUser.contentHeight)];
        }
    }
}

- (void)viewSafeAreaInsetsDidChange {
    [super viewSafeAreaInsetsDidChange];
    CGSize size = self.view.bounds.size;
    if ([[[XLAccountManager shareInstance] model].IsAnchor integerValue] == 10) {
        
        _tableView.frame = CGRectMake(0, 0, size.width, size.height - _inputView.contentHeight - self.view.safeAreaInsets.bottom);
        [_inputView setFrameAndLayout:CGRectMake(0, size.height - _inputView.contentHeight - self.view.safeAreaInsets.bottom, size.width, _inputView.contentHeight)];
    }else{
        _tableView.frame = CGRectMake(0, 0, size.width, size.height - _input2ViewUser.contentHeight - self.view.safeAreaInsets.bottom);
        [_input2ViewUser setFrameAndLayout:CGRectMake(0, size.height - _input2ViewUser.contentHeight - self.view.safeAreaInsets.bottom, size.width, _input2ViewUser.contentHeight)];
    }
}

-(void)hiddenKeyBoard
{
    //    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
    if ([[[XLAccountManager shareInstance] model].IsAnchor integerValue] == 10) {
        
        [_inputView resignFirstResponder];
    }else{
        [_input2ViewUser resignFirstResponder];
    }
}

- (void)onChatInput:(UIView<ChatInputAbleView> *)chatInput sendMsg:(IMAMsg *)text
{
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]) {//
        [self sendMsg:text];
        return;
    }
    if(ValidStr(self.isAnchor_rec))
    {
        if([self.isAnchor_rec isEqualToString:@"0"])
        {
            [self sendMsg:text];
            return;
        }
    }else
    {
        kWeakSelf(self);
        [self getIsAnchorWithUserID:_receiver.userId Complete:^(NSString *isAnchor) {
            weakself.isAnchor_rec = isAnchor;
            if([weakself.isAnchor_rec isEqualToString:@"0"])
            {
                [weakself sendMsg:text];
                return;
            }
        }];
    }
    //发送信息确认是否有足够的金豆支付
        [self reqeustSource];
    
        //存在豆子 并且 请求数据是成功的！
        if (beansCount <= 0 && requestSucess == YES) {
            return;
        }
    
        [self sendMsg:text];
        NSMutableArray *elems = [NSMutableArray array];
        for (int index =0 ; index<text.msg.elemCount; index++ )
        {
            [elems addObject:[text.msg getElem:index]];
        }
    
        beansCount--;
        if (beansCount <= 0) {
            beansCount = 0;
        }
    
    NSLog(@"%d",text.msg.elemCount);
}

-(void)judgeBalanceWithMsg:(IMAMsg *)msg
{
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]) {//
        [self sendMsg:msg];
        return;
    }
    //发送信息确认是否有足够的金豆支付
    if(ValidStr(self.isAnchor_rec))
    {//如果接收方是用户  则不需要扣费  直接发送
        if([self.isAnchor_rec isEqualToString:@"0"])
        {
            [self sendMsg:msg];
            return;
        }
    }else
    {
        kWeakSelf(self);
        [self getIsAnchorWithUserID:_receiver.userId Complete:^(NSString *isAnchor) {
            weakself.isAnchor_rec = isAnchor;
            if([weakself.isAnchor_rec isEqualToString:@"0"])
            {
                [weakself sendMsg:msg];
                return;
            }
        }];
    }
    
    //判断主播 / 用户
    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"]) {
        //如果是主播  直接发送消息  不用扣除金豆
        [self sendMsg:msg];
        return;
    }
    if(requestSucess == YES)
    {
        if(beansCount <= 0)
        {
            //金豆不够使用
            UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"金豆余额不足" message:@"快去充值开启你的畅聊吧" preferredStyle:(UIAlertControllerStyleAlert)];
            
            UIAlertAction *alertRecharge = [UIAlertAction actionWithTitle:@"充值" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                
                //跳转充值界面
                TopUpViewController *topViewVc = [[TopUpViewController alloc] init];
                [self.navigationController pushViewController:topViewVc animated:YES];
                
            }];
            
            UIAlertAction *alertCancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            
            //添加弹窗事件
            [alertVc addAction:alertRecharge];
            [alertVc addAction:alertCancel];
            
            [self presentViewController:alertVc animated:YES completion:^{
                
            }];
        }else
        {
            [self sendMsg:msg];
            beansCount--;
            if (beansCount <= 0) {
                beansCount = 0;
            }
        }
    }else
    {
        [[[XLHTTPSessionManager sharedManager] XLV2GET:@"/api/v2/Balance/GetUserBalance" parameters:@{@"userId":[[XLAccountManager shareInstance]model].Id} resultClass:nil]subscribeNext:^(id x) {
            NSDictionary *dic = x;
            
            requestSucess = YES;
            
            //获取金豆总数
            NSString *totalMoney = [NSString stringWithFormat:@"%.1lf",[[dic objectForKey:@"AccountBalance"] floatValue]];
            
            CGFloat beans = [totalMoney floatValue]*10;
            beansCount = beans;
            
            
            if (beansCount <= 0 && requestSucess == YES) {
                
                //金豆不够使用
                UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"金豆余额不足" message:@"快去充值开启你的畅聊吧" preferredStyle:(UIAlertControllerStyleAlert)];
                
                UIAlertAction *alertRecharge = [UIAlertAction actionWithTitle:@"充值" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                    
                    //跳转充值界面
                    TopUpViewController *topViewVc = [[TopUpViewController alloc] init];
                    [self.navigationController pushViewController:topViewVc animated:YES];
                    
                }];
                
                UIAlertAction *alertCancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                
                //添加弹窗事件
                [alertVc addAction:alertRecharge];
                [alertVc addAction:alertCancel];
                
                [self presentViewController:alertVc animated:YES completion:^{
                    
                }];
            }else if(beansCount > 0 && requestSucess == YES)
            {
                //存在豆子 并且 请求数据是成功的！
                if (beansCount <= 0 && requestSucess == YES) {
                    return;
                }
                [self sendMsg:msg];
                beansCount--;
                if (beansCount <= 0) {
                    beansCount = 0;
                }
            }
            else{
                //请求失败 可以发送消息
                if (requestSucess == NO) {
                    beansCount = 10;
                }else{
                    beansCount = beans;
                }
                
            }
            
        } error:^(NSError *error) {
            NSDictionary *dic = nil;
            requestSucess = NO;
            //获取金豆总数
            NSString *totalMoney = [NSString stringWithFormat:@"%.1lf",[[dic objectForKey:@"AccountBalance"] floatValue]];
            
            CGFloat beans = [totalMoney floatValue]*10;
            beansCount = beans;
            
            
            if (beansCount <= 0 && requestSucess == YES) {
                
                //金豆不够使用
                UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"金豆余额不足" message:@"快去充值开启你的畅聊吧" preferredStyle:(UIAlertControllerStyleAlert)];
                
                UIAlertAction *alertRecharge = [UIAlertAction actionWithTitle:@"充值" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                    
                    //跳转充值界面
                    TopUpViewController *topViewVc = [[TopUpViewController alloc] init];
                    [self.navigationController pushViewController:topViewVc animated:YES];
                    
                }];
                
                UIAlertAction *alertCancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                
                //添加弹窗事件
                [alertVc addAction:alertRecharge];
                [alertVc addAction:alertCancel];
                
                [self presentViewController:alertVc animated:YES completion:^{
                    
                }];
            }else{
                
                //请求失败 可以发送消息
                if (requestSucess == NO) {
                    beansCount = 10;
                }else{
                    beansCount = beans;
                }
                
            }
            
        }];
    }
    
}


- (void)onChatInput:(UIView<ChatInputAbleView> *)chatInput willSendMsg:(IMAMsg *)msg
{
    if (msg)
    {
        [_tableView beginUpdates];
        
        NSArray *newaddMsgs = [_conversation appendWillSendMsg:msg completion:nil];
        
        NSMutableArray *array = [NSMutableArray array];
        for (IMAMsg *msg in newaddMsgs)
        {
            NSInteger idx = [_messageList indexOfObject:msg];
            NSIndexPath *index = [NSIndexPath indexPathForRow:idx inSection:0];
            [array addObject:index];
        }
        
        [_tableView insertRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationFade];
        [_tableView endUpdates];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSIndexPath *index = [NSIndexPath indexPathForRow:_messageList.count - 1 inSection:0];
            [_tableView scrollToRowAtIndexPath:index atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        });
    }
}

- (void)onReplaceDelete:(NSArray *)replaceMsgs
{
    if (replaceMsgs.count)
    {
        [_tableView beginUpdates];
        NSMutableArray *addIndexs = [NSMutableArray array];
        for (IMAMsg *msg in replaceMsgs)
        {
            NSInteger index = [_messageList indexOfObject:msg];
            [addIndexs addObject:[NSIndexPath indexPathForRow:index inSection:0]];
        }
        // 说明只是替换最后一个
        [_tableView reloadRowsAtIndexPaths:addIndexs withRowAnimation:UITableViewRowAnimationFade];
        [_tableView endUpdates];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSIndexPath *index = [NSIndexPath indexPathForRow:_messageList.count - 1 inSection:0];
            [_tableView scrollToRowAtIndexPath:index atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        });
    }
}

- (void)onChatInput:(UIView<ChatInputAbleView> *)chatInput replaceWith:(IMAMsg *)newMsg oldMsg:(IMAMsg *)msg
{
    if (msg)
    {
        __weak IMAChatViewController *ws = self;
        [_conversation replaceWillSendMsg:msg with:newMsg completion:^(NSArray *imamsgList, BOOL succ, IMAMsg *msg) {
            if (succ)
            {
                [ws onReplaceDelete:imamsgList];
            }
        }];
    }
}

- (void)onWillRemove:(NSArray *)imamsgList withAction:(NormalVoidBlock)action
{
    [_tableView beginUpdates];
    
    NSMutableArray *indexArray = [NSMutableArray array];
    
    for (IMAMsg *removemsg in imamsgList)
    {
        NSInteger idx = [_messageList indexOfObject:removemsg];
        NSIndexPath *index = [NSIndexPath indexPathForRow:idx inSection:0];
        [indexArray addObject:index];
    }
    
    if (action)
    {
        action();
    }
    
    [_tableView deleteRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationNone];
    
    [_tableView endUpdates];
    
    
    
}
- (void)onChatInput:(UIView<ChatInputAbleView> *)chatInput cancelSendMsg:(IMAMsg *)msg
{
    if (msg)
    {
        __weak IMAChatViewController *ws = self;
        [_conversation removeMsg:msg completion:^(NSArray *imamsgList, BOOL succ, NormalVoidBlock removingAction) {
            if (succ)
            {
                [ws onWillRemove:imamsgList withAction:removingAction];
            }
        }];
        
    }
}

//收费图片(聊天界面按钮）
- (void)onChatInputSendMoneyImage:(UIView<ChatInputAbleView> *)chatInput
{
    [self moreViewMoneyImageAction];
}

//收费视频
- (void)onChatInputSendMoneyVideo:(UIView<ChatInputAbleView> *)chatInput
{
    [self moreViewMoneyVideoAction];
}

//免费图片
- (void)onChatInputSendFreeImage:(UIView<ChatInputAbleView> *)chatInput
{
    [self moreViewFreeImageAction];
}

//视频通话
- (void)onChatInputChatVideo:(UIView<ChatInputAbleView> *)chatInput
{
    [self moreVideChatVideoAction];
}
- (void)onChatInputChatVoice:(UIView<ChatInputAbleView> *)chatInput {
    [self moreVideChatVoiceAction];
}
- (void)onChatInputFlower:(UIView<ChatInputAbleView> *)chatInput {//如果是用户的话就调用视频通话
    if ([[[XLAccountManager shareInstance] model].IsAnchor integerValue] == 1) {
        [MBProgressHUD showContent:@"主播暂不支持呼叫"];
        //        [self moreVideFlowerAction];
    }else{
        [self moreVideChatVideoAction];
    }
}
@end
